﻿

namespace Mulala.Cavan.Application.MainBoundedContext.CorporationModule
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Mulala.Cavan.Application.MainBoundedContext.AttachmentModule;
    using Mulala.Cavan.Application.MainBoundedContext.LogModule;
    using Mulala.Cavan.Application.MainBoundedContext.MulalaModule;
    using Mulala.Cavan.Application.MainBoundedContext.SecurityModule;
    using Mulala.Cavan.Application.Seedwork;
    using Mulala.Cavan.Core.Helper;
    using Mulala.Cavan.Domain.MainBoundedContext.AttachmentModule;
    using Mulala.Cavan.Domain.MainBoundedContext.CorporationModule;
    using Mulala.Cavan.Domain.MainBoundedContext.DictionaryModule;
    using Mulala.Cavan.Domain.MainBoundedContext.LogModule;
    using Mulala.Cavan.Domain.MainBoundedContext.MulalaModule;
    using Mulala.Cavan.Domain.MainBoundedContext.SearchModule;
    using Mulala.Cavan.Domain.Seedwork;
    using Spring.Context;
    using Spring.Context.Support;

    public class CorporationAppService : BaseAppService<Corporation, CorporationSearch, ICorporationRepository>, ICorporationAppService
    {
        private IApplicationContext SpringContext = null;
        private ICorporationStatusRepository CorporationStatusRepository { get; set; }
        private ICorporationCommentRepository CorporationCommentRepository { get; set; }
        private ICorporationNewRepository CorporationNewRepository { get; set; }
        private ITagAppService TagAppService { get; set; }
        private IAttachmentAppService AttachmentAppService { get; set; }
        private IVisitHistoryAppService VisitHistoryAppService { get; set; }
        private IAreaAppService AreaAppService { get; set; }

        public CorporationAppService()
        {
        }

        #region ICorporationAppService Members

        public Corporation GetCorporationById(int id)
        {
            Corporation corporation = base.GetById(id);
            corporation.ViewTotal = corporation.ViewTotal + 1;

            this.Repository.Update(corporation);
            this.LogVisitHistory(corporation);

            return corporation;
        }

        public override BoolGenericResult<Corporation> Update(Corporation changedCorporation)
        {
            this.SpringContext = ContextRegistry.GetContext();
            this.AreaAppService = this.SpringContext.GetObject(MulalaAppServiceConst.AREAAPPSERVICE) as IAreaAppService;

            BoolGenericResult<Corporation> result = new BoolGenericResult<Corporation>();
            Corporation currentCorporation = this.Repository.Get(changedCorporation.ID);
            changedCorporation.Area = this.AreaAppService.GetById(changedCorporation.Area.ID);

            result = currentCorporation.ModifyInfo(changedCorporation.FullName, changedCorporation.Area, changedCorporation.RegistrationTime,
                                                    changedCorporation.Type, changedCorporation.Nature, changedCorporation.BusinessExperience, changedCorporation.Scale,
                                                    changedCorporation.Speciality, changedCorporation.Contact, changedCorporation.ContactEmail,
                                                    changedCorporation.Address, changedCorporation.Telephone, changedCorporation.Mobile,
                                                    changedCorporation.Fax, changedCorporation.Introduce, changedCorporation.Culture, changedCorporation.Capital,
                                                    changedCorporation.ChargeDescription, changedCorporation.HomePage, changedCorporation.BusinessLicence, changedCorporation.CustomService);

            if (result.IsSuccess)
            {
                this.Repository.Update(currentCorporation);
            }

            result.Messages.Add("保存成功");
            return result;
        }

        public bool UpdateCorporationStatus(CorporationStatus changedCorporationStatus)
        {
            this.CorporationStatusRepository.Update(changedCorporationStatus);

            return true;
        }

        public IList<Corporation> GetCorporationsByKeyword(string keyword, int currentPage, out long total)
        {
            CorporationSearch corporationSearch = ParseKeywordToCorporationSearch(keyword);

            return this.GetBySearch(corporationSearch, out total).ToList();
        }

        public BoolGenericResult<Attachment> UpdateCorporationLogo(Corporation changedCorporation, string fileUrl, string fileName)
        {
            this.SpringContext = ContextRegistry.GetContext();
            this.AttachmentAppService = this.SpringContext.GetObject(MulalaAppServiceConst.ATTACHMENTAPPSERVICE) as IAttachmentAppService;

            BoolGenericResult<Attachment> result = new BoolGenericResult<Attachment>();
            Attachment logo = changedCorporation.Attachments.FirstOrDefault(a => a.AttachmentGroup == AttachmentIdentifier.AttachmentGroup.CorporationLogo);

            if (null == logo)
            {
                logo = AttachmentFactory.CreateAttachment(AttachmentIdentifier.AttachmentGroup.CorporationLogo, changedCorporation.ID, fileName, fileUrl, true, AttachmentIdentifier.CheckedStatus.UnChecked,
                    false, 1, DateTime.Now, changedCorporation.UserAccount.Name);
                this.AttachmentAppService.Add(logo);

                result.Object = logo;
            }
            else
            {
                result = changedCorporation.ModifyLogo(fileUrl, fileName);
                if (result.IsSuccess)
                {
                    this.AttachmentAppService.Update(result.Object);
                }
            }
            result.Messages.Add("保存成功！");
            return result;
        }

        public BoolGenericResult<Attachment> UpdateCorporationCertification(Corporation changedCorporation, int certificationID, string fileUrl, string fileName)
        {
            this.SpringContext = ContextRegistry.GetContext();
            this.AttachmentAppService = this.SpringContext.GetObject(MulalaAppServiceConst.ATTACHMENTAPPSERVICE) as IAttachmentAppService;

            BoolGenericResult<Attachment> result = new BoolGenericResult<Attachment>();
            Attachment certification = changedCorporation.Attachments.FirstOrDefault(a => a.ID == certificationID && a.AttachmentGroup == AttachmentIdentifier.AttachmentGroup.CorporationCertification);

            if (null == certification)
            {
                result = changedCorporation.UploadCertification(fileUrl, fileName);

                this.AttachmentAppService.Add(result.Object);
            }
            else
            {
                result = changedCorporation.ModifyCertification(certificationID, fileUrl, fileName);
                if (result.IsSuccess)
                {
                    this.AttachmentAppService.Update(result.Object);
                }
            }
            result.Messages.Add("保存成功！");
            return result;
        }

        public BoolGenericResult<Attachment> UpdateCorporationPhoto(Corporation changedCorporation, int photoID, string fileUrl, string fileName)
        {
            this.SpringContext = ContextRegistry.GetContext();
            this.AttachmentAppService = this.SpringContext.GetObject(MulalaAppServiceConst.ATTACHMENTAPPSERVICE) as IAttachmentAppService;

            BoolGenericResult<Attachment> result = new BoolGenericResult<Attachment>();
            Attachment photo = changedCorporation.Attachments.FirstOrDefault(a => a.ID == photoID && a.AttachmentGroup == AttachmentIdentifier.AttachmentGroup.CorporationPhoto);

            if (null == photo)
            {
                result = changedCorporation.UploadPhoto(fileUrl, fileName);

                this.AttachmentAppService.Add(result.Object);
            }
            else
            {
                result = changedCorporation.ModifyPhoto(photoID, fileUrl, fileName);
                if (result.IsSuccess)
                {
                    this.AttachmentAppService.Update(result.Object);
                }
            }
            result.Messages.Add("保存成功！");
            return result;
        }

        public BoolGenericResult<CorporationStatus> UpdateCorporationRefreshTime(Corporation changedCorporation)
        {
            BoolGenericResult<CorporationStatus> result = new BoolGenericResult<CorporationStatus>();
            Corporation corporation = this.Repository.Get(changedCorporation.ID);
            result = corporation.RefreshSelf();

            if (result.IsSuccess)
            {
                this.CorporationStatusRepository.Update(result.Object);
            }
            result.Messages.Add("刷新成功");
            return result;
        }

        private CorporationSearch ParseKeywordToCorporationSearch(string keyword)
        {
            this.SpringContext = ContextRegistry.GetContext();
            this.TagAppService = this.SpringContext.GetObject(MulalaAppServiceConst.TAGAPPSERVICE) as ITagAppService;
            CorporationSearch corporationSearch = new CorporationSearch();
            string[] keywords = StringHelper.ClearExtraSpace(keyword).Split(' ');
            List<int> skillPositions = new List<int>();
            foreach (string kw in keywords)
            {
                TagSearch tagSearch = TagSearchFactory.CreateTagSearch(kw);
                Tag tag = this.TagAppService.GetSingleBySearch(tagSearch);
                if (null != tag)
                {
                    if (tag.TagGroup.ID == DictionaryIdentifier.GroupType.NannyType.GetHashCode())
                    {
                        corporationSearch.Type = (CorporationIdentifier.CorporationType)int.Parse(tag.Value);
                    }
                    else if (tag.TagGroup.ID == DictionaryIdentifier.GroupType.NannySkill.GetHashCode())
                    {
                        skillPositions.Add(tag.BinaryPosition);
                    }
                }
            }
            if (skillPositions.Count > 0)
            {
                corporationSearch.SkillPosition = skillPositions.ToArray();
            }
            return corporationSearch;
        }

        private void LogVisitHistory(Corporation corporation)
        {
            this.SpringContext = ContextRegistry.GetContext();
            this.VisitHistoryAppService = this.SpringContext.GetObject(MulalaAppServiceConst.VISITHISTORYAPPSERVICE) as IVisitHistoryAppService;

            if (SecurityAppService.IsLogon)
            {
                VisitHistorySearch visitHistorySearch = new VisitHistorySearch();
                visitHistorySearch.IntervieweeID = corporation.ID;
                visitHistorySearch.VisitorID = SecurityAppService.UserAccount.ID;
                VisitHistory visitHistory = this.VisitHistoryAppService.GetSingleBySearch(visitHistorySearch);
                if (null == visitHistory)
                {
                    this.VisitHistoryAppService.AddVisitHistory(corporation.UserAccount, CavanWebUtility.GetUserIP(), SecurityAppService.UserAccount);
                }
                else
                {
                    visitHistory.LastVisitTime = DateTime.Now;
                    this.VisitHistoryAppService.Update(visitHistory);
                }
            }
        }
        #endregion
    }
}
